package ai.leinao.alarm.limit;

import ai.leinao.alarm.domain.AlarmSilence;
import ai.leinao.alarm.domain.GroupAlarm;
import ai.leinao.alarm.service.AlarmSilenceService;
import ai.leinao.notify.core.Notifier;
import ai.leinao.notify.core.NotifierRegistry;
import ai.leinao.notify.core.enums.NotifyType;
import ai.leinao.notify.core.template.Template;
import ai.leinao.notify.core.template.TemplateRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 告警静默处理
 *
 * @author zhong.wang
 * @date 2025/9/3
 **/
@Component
@Slf4j
public class AlarmSilenceProcessor {
    private final  List<AlarmSilence> alarmSilenceList;

    private final AlarmSilenceService alarmSilenceService;

    private final NotifierRegistry notifierRegistry;

    private final TemplateRegistry templateRegistry;

    public AlarmSilenceProcessor(AlarmSilenceService alarmSilenceService, NotifierRegistry notifierRegistry, TemplateRegistry templateRegistry) {
        this.notifierRegistry = notifierRegistry;
        this.templateRegistry = templateRegistry;
        this.alarmSilenceList = new ArrayList<>();
        this.alarmSilenceService = alarmSilenceService;
        initAlarmSilenceList();
    }

    /**
     * 初始化静默规则列表
     */
    private void initAlarmSilenceList() {
        alarmSilenceList.addAll(alarmSilenceService.getAlarmSilences());
    }

    /**
     * 使用静默规则处理告警
     * 如果告警匹配任何生效的静默规则，则该告警将被静默
     * @param groupAlert 需要处理的告警
     */
    public void silenceAlarm(GroupAlarm groupAlert) {
        //log.info("开始处理告警静默规则 ...");
        // 检查silence规则
        for (AlarmSilence alarmSilence : alarmSilenceList) {
            // Check if alert matches silence rule
            boolean match = false;
            if (!match && groupAlert.getGroupLabels() != null) {
                Map<String, String> labels = alarmSilence.getLabels();
                Map<String, String> alertLabels = groupAlert.getGroupLabels();
                match = labels.entrySet().stream().allMatch(item ->
                        alertLabels.containsKey(item.getKey()) && item.getValue().equals(alertLabels.get(item.getKey())));
            }

            if (match) {
                LocalDateTime now = LocalDateTime.now();
                // Cyclic silence rule
                int currentDayOfWeek = now.getDayOfWeek().getValue();
                if (alarmSilence.getDays() != null && alarmSilence.getDays().contains(currentDayOfWeek)
                            && !check(now, alarmSilence)) {
                    return;
                }
            }
        }

        log.info("接收到告警:{},alarmFingerprints:{}", groupAlert.getGroupKey(),groupAlert.getAlarmFingerprints().size());
//        Notifier dbAlarmEmail = notifierRegistry.getNotifier(NotifyType.EMAIL, "dbAlarmEmail");
//        Template dbAlarmEmailTemplate = templateRegistry.getTemplate(NotifyType.EMAIL, "dbAlarmEmail");
//        Map<String, Object> context = new HashMap<>();
//        context.put("groupKey", groupAlert.getGroupKey());
//        context.put("alarms", groupAlert.getAlarms().toString());
//        context.put("sendTo", "wangzhongwang@leinao.ai");
//        dbAlarmEmail.send(dbAlarmEmailTemplate, context);
    }

    /**
     * 检查告警时间是否在静默时间段内，并更新静默规则计数器
     * @param now 当前时间
     * @param alarmSilence 需要检查的静默规则
     * @return 如果告警不应被静默则返回true，如果告警应被静默则返回false
     */
    private boolean check(LocalDateTime now, AlarmSilence alarmSilence) {
        boolean startMatch = alarmSilence.getPeriodStart() == null
                || now.isAfter(alarmSilence.getPeriodStart().toLocalDateTime());
        boolean endMatch = alarmSilence.getPeriodEnd() == null
                || now.isBefore(alarmSilence.getPeriodEnd().toLocalDateTime());

        if (startMatch && endMatch) {
            return false;
        }
        return true;
    }
}
